/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author Frank
 */
public class VertaalClient {
    
    private Socket socket = null;
    private PrintWriter uit = null;
    private BufferedReader in = null;
    private Gui gui;
    
    public VertaalClient(Gui gui) {
        
        this.gui = gui;
        this.gui.addVertaalClient(this);
        
        this.maakVerbinding();
        handleRequest();
            
    }
    
    private void maakVerbinding() {
        
        try {
            
            // Socket aanmaken
            this.socket = new Socket(Settings.hostname, Settings.port);
            
            // Streams aanmaken
            this.uit = new PrintWriter(this.socket.getOutputStream(), true);
            this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
            
        } catch(UnknownHostException e) {
            System.out.println("Host niet gevonden");
            System.exit(1);
        } catch(IOException e) {
            System.out.println("Connectie error");
            System.exit(1);
        }
        
    }
    
    public void sendMessage(String text) {
        
        if(uit != null) {
            
            // Verstuur bericht naar server
            uit.println(text); 
            
        }
        
    }
    
    private void handleRequest() {
        
        try {
        
            BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
            String serverBericht;
            String userBericht;
            String handledText = "";
            
            // We vangen de response van de server af
            while((serverBericht = in.readLine()) != null) {
                
                // We stoppen met luisteren naar server
                if(serverBericht.equals("exit")) {
                    break;
                } else {
                    
                    // Bericht van de server plaatsen in de console
                    this.gui.addConsole(serverBericht);
                    
                }
                
            }
            
            this.uit.close();
            this.in.close();
            stdIn.close();
            this.socket.close();
            
        } catch(IOException e) {
            System.out.println(e);
        }
        
    }
    
}
